package net.yuyoo.uusession.support;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class HashUtil {
	
	private static MessageDigest md5 = null;

	static {
		
		try {
			md5 = MessageDigest.getInstance("MD5");
		} catch (NoSuchAlgorithmException e) {
			throw new RuntimeException("MD5 not supported", e);
		}
	}
	
	public static long getConsistentHash(String key) {
		
		try {
			byte[] rtv = null;
			synchronized (md5) { // md5 implement is un-thread-safty
				md5.reset();
				byte[] codes = null;
				try {
					codes = key.getBytes("UTF-8");
				} catch (UnsupportedEncodingException ex) {
					new RuntimeException(ex);
				}
				md5.update(codes);
				rtv = md5.digest();
			} 
			
			long b0 = rtv[0];
			long b1 = rtv[1];
			long b2 = rtv[2];
			long b3 = rtv[3];
			
			return (b0 << 24) + (b1 << 16) + (b2 << 8) + b3; 
		} catch (Exception ex) {
			throw new RuntimeException("MD5 not supported", ex);
		}
	}
	
	public static long getDJBHash(String key) {
		
		long hash = 5381;
		for (int i = 0; i < key.length(); i++) {
			hash = ((hash << 5) + hash) + key.charAt(i);
		}
		return hash;
	} 
}
